<template>
  <Modal
    v-model="addClassModal.show"
    :title="addClassModal.title"
    :loading="addClassModal.loading"
    :mask-closable="false"
    width="1100px"
  >
    <div class="header-wrapper flex-between">
      <div class="step-group">
        <Button
          :type="addClassModal.step === 1 ? 'primary' : 'text'"
          class="base-info mr10"
          @click="intoStep(1)"
          :disabled="!allowStep"
          >{{pageSTitle}}基础信息</Button
        >
        <Button
          :type="addClassModal.step === 2 ? 'primary' : 'text'"
          class="time-plan"
          @click="intoStep(2)"
          >{{pageSTitle}}内容及时间安排</Button
        >
      </div>
      <div class="search-wrapper flex" v-if="addClassModal.step === 2">
        <!-- <p style="color:#f90">
                    <Icon type="ios-information-circle" />请选择技能树开始创建数据
                </p> -->
        <Button size="small" type="primary" @click="showAddModal"
          >创建{{pageSTitle}}内容</Button
        >
        <AddContentModal
          v-model="addModal.show"
          :egId="formValidate.id"
          :selectPlanList="planValidate.planList"
          @selection-change="addTrain"
        ></AddContentModal>
        <!-- <Select filterable
                    v-model="addClassModal.query.skillId"
                    placeholder="请选择技能树"
                    @on-change="getSkillDtail"
                    style="width:150px;margin-left:15px"
                    clearable
                >
                    <Option
                        v-for="skill in addClassModal.skillList"
                        :value="skill.id"
                        :key="skill.id"
                        >{{ skill.name }}</Option
                    >
                </Select> -->
      </div>
    </div>
    <Form
      ref="formValidate"
      :model="formValidate"
      :rules="ruleValidate"
      :label-width="95"
      v-show="addClassModal.step === 1"
    >
      <FormItem :label="pageSTitle+'名称'" prop="egName">
        <Input
          v-model.trim="formValidate.egName"
          placeholder='名称不能包含下列任意英文字符 \ / : * ? " < > |，长度为1-128个字符'
        ></Input>
      </FormItem>
      <FormItem label="实验组" prop="groupIdList">
        <Select filterable
          v-model="formValidate.groupIdList"
          placeholder="请选择实验组"
          @on-change="changeGroup"
          filterable
          multiple
        >
          <!--    :disabled="addClassModal.type == 2" -->
          <Option
            :value="group.id"
            v-for="group in expGroupList"
            :key="group.id"
            :title="group.name"
            >{{ group.name }}</Option
          >
        </Select>
      </FormItem>
      <FormItem
        label="实验组及成员"
        prop="groupList"
        key="groupList"
        v-show="formValidate.groupIdList.length > 0"
      >
        <Card
          dis-hover
          v-for="group in formValidate.groupList"
          :key="group.id"
          class="mb10 card-small flex class-card"
        >
          <template slot="title">
            <!-- <small style="font-size: 12px;">实验组： </small> -->
            <Checkbox
              style="margin-right: 0"
              :value="group.checkAll"
              @click.prevent.native="handleCheckAll(group)"
              :disabled="group.disabled"
            >
              <Tooltip
                :content="group.name"
                placement="top"
                style="vertical-align: middle"
              >
                <span class="text-ellipsis" style="width: 70px">{{
                  group.name
                }}</span>
              </Tooltip></Checkbox
            >
          </template>
          <CheckboxGroup
            v-model="group.userIds"
            @on-change="handleGroupChange($event, group)"
          >
            <!-- <small style="font-size: 12px;">成员：</small> -->
            <Checkbox
              :label="user.userId"
              v-for="user in group.userList"
              :key="user.userId"
              :disabled="disUserSelect(user, group) || group.disabled"
              >{{ user.userName }}</Checkbox
            >
          </CheckboxGroup>
          <!--</div>-->
        </Card>
      </FormItem>
      <FormItem label="描述" prop="description">
        <Input
          v-model.trim="formValidate.description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 5 }"
        ></Input>
      </FormItem>
    </Form>
    <Form
      v-if="addClassModal.step === 2"
      ref="planValidate"
      :model="planValidate"
      :rules="ruleValidate"
      :label-width="0"
      class="time-plan-wrapper"
    >
      <!-- <p>{{ planValidate.planList }}</p>
            <p style="background:red">{{ planValidate.selectPlans }}</p> -->
      <div
        class="header-wrapper flex-between mt10 mb10"
        v-if="planValidate.planTotal > 0"
      >
        <h4 class="flex">
          创建{{pageSTitle}}内容
          <WarningTip
            placement="right"
            :content="`${teachingText}开始时间不能小于当前时间，开始时间不能等于结束时间，`"
          ></WarningTip>
          <!-- <p style="color:#f90">
                        <Icon
                            type="ios-information-circle"
                        />培训开始时间不能小于当前时间，开始时间不能等于结束时间，培训时间不能冲突
                    </p> -->
        </h4>
        <div>
          <Poptip confirm title="确定删除选中的数据吗?" @on-ok="delSelect">
            <Button
              type="error"
              size="small"
              :disabled="
                !planValidate.selectPlans ||
                planValidate.selectPlans.length <= 0
              "
              >删除</Button
            >
          </Poptip>
        </div>
        <!--   :disabled="planValidate.selectPlans && planValidate.selectPlans.length <= 0" -->
      </div>
      <TableList
        :data="planValidate.planList"
        :total="planValidate.planTotal"
        :showPage="false"
        :showDef="false"
        :columns="planCol"
        :showLoading="false"
        selectKey="id"
        ref="selectTable"
        :selection.sync="planValidate.selectPlans"
      ></TableList>
      <p v-if="timeTip" class="mt10" style="color: #ed4014">{{ timeTip }}</p>
      <!--  @selection-change="selectData" -->
    </Form>
    <SavePlanList
      :id="this.formValidate.id"
      v-if="this.addClassModal.step === 2"
    ></SavePlanList>
    <template slot="footer">
      <Button
        type="primary"
        @click="switchStep()"
        :loading="stepLoading"
        :disabled="!allowStep && addClassModal.step === 1"
        ><template v-if="addClassModal.step === 1">下一步</template
        ><template v-if="addClassModal.step === 2">上一步</template></Button
      >
      <Button @click="addClassModal.show = false">取消</Button>
      <Button
        @click="saveTeachSchedule()"
        v-if="addClassModal.step === 2"
        :loading="confirmLoading"
        >确定</Button
      >
    </template>
  </Modal>
</template>
<script>
import moment from 'moment';
import encryption from '@/libs/encryption.js';
import SavePlanList from './save-plan-list';
//接口
import { queryExperGroups, getExperGroupsUsers } from '@/api/users';
import { querySkill, querySkillBindDetail } from '@/api/selfStudy/skill.js';
import {
    addClass,
    modifyClass,
    queryClassInfo,
    addTeachSchedule,
    queryTeachSchedule
} from '@/api/selfStudy/class_new.js';
import { getGroupInfo, addGroup, updateGroup } from '@/api/boardcast_new.js';
import typeMixin from '../mixins/typeMixin';
import AddContentModal from './add-content-modal';
import trainSceneVue from '../../../train/trainScene.vue';
import {validateName1,validateName128 } from '@/libs/reg.js'
export default {
    name: 'EditModal',
    components: { SavePlanList, AddContentModal },
    mixins: [typeMixin],
    props: {
        value: {
            type: Boolean,
            default: false
        },
        type: {
            type: String,
            default: false,
            validator(value) {
                return ['add', 'update'].includes(value);
            }
        },
        data: {
            type: [Object, String]
        }
    },
    data() {
        let _this = this;
        const validateName = (rule, value, callback) => {
            //验证只能填入数字
            var reg = new RegExp('^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$');
            //验证警戒值
            if (value) {
                if (!reg.test(value)) {
                    callback(new Error('请输入中文、数字、字母、下划线、-'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validateGroup = (rule, value, callback) => {
            //验证警戒值
            let _this = this;
            if (_this.formValidate.groupIdList.length <= 0) {
                callback(new Error('请选择实验组'));
            } else {
                callback();
            }
        };
        const validateGroupUserNum = (rule, value, callback) => {
            //验证警戒值
            let _this = this;
            if (_this.formValidate.groupList.length > 0) {
                if (_this.formValidate.groupList.some((group) => group.userIds.length == 0)) {
                    callback(new Error('每个班级请至少选择一个成员'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
        const validateTime = (rule, value, callback, row) => {
            //验证警戒值
            let _this = this;
            let length = _this.planValidate.planList.length;
            let preEnd = row._index > 0 ? _this.planValidate.planList[row._index - 1] : '';
            let nextStart =
                row._index < length - 1 ? _this.planValidate.planList[row._index + 1] : '';
            if (!value || value.length != 2) {
                _this.planValidate.planList[row._index].timeTip = row.timeTip = '时间不能为空';
                console.log('时间不能为空');
                callback(new Error('时间不能为空'));
            } else if (value.length > 0) {
                let startTime = new Date(value[0]).getTime();
                let endTime = new Date(value[1]).getTime();
                if (startTime < new Date().getTime()) {
                    _this.planValidate.planList[row._index].timeTip = row.timeTip =
                        '开始时间不能小于当前时间';
                    callback(new Error('开始时间不能小于当前时间'));
                } else if (startTime === endTime) {
                    _this.planValidate.planList[row._index].timeTip = row.timeTip =
                        '结束时间不能等于开始时间';
                    callback(new Error('结束时间不能等于开始时间'));
                // } else if (preEnd && startTime < new Date(preEnd.time[1]).getTime()) {
                //     _this.planValidate.planList[row._index].timeTip = row.timeTip = this.teachingText + '时间冲突';
                //     callback(new Error(this.teachingText + '时间冲突'));
                // } else if (nextStart && endTime > new Date(nextStart).getTime()) {
                //     _this.planValidate.planList[row._index].timeTip = row.timeTip = this.teachingText + '时间冲突';
                //     callback(new Error(this.teachingText + '时间冲突'));
                } else {
                    _this.planValidate.planList[row._index].timeTip = row.timeTip = '';
                    callback();
                }
            } else {
                _this.planValidate.planList[row._index].timeTip = row.timeTip = '';
                callback();
            }
        };
        return {
            addModal: {
                show: false,
                data: []
            },
            addClassModal: {
                show: this.value,
                title: '创建'+this.pageSTitle,
                loading: true,
                step: 1,
                courseList: [],
                expList: [],
                skillList: [], //技能书列表
                query: { skillId: '' }
            },
            expGroupList: [],
            formValidate: {
                description: '',
                egName: '',
                teacherName: '',
                userList: [],
                selectUsers: [],
                groupIdList: [],
                groupList: [],
                trainUserTOS: [
                    {
                        groupId: '',
                        groupName: '',
                        userId: '',
                        userName: ''
                    }
                ]
            },
            planValidate: {
                planList: [],
                selectPlans: [],
                planTotal: 0,
                savedPlanInfo: {
                    list: [],
                    total: '',
                    page: 1,
                    size: 10
                } //已保存的课节课节列表
            },
            curModPlan: [],
            curTime: [],
            ruleValidate: {
                egName: [
                    {
                        required: true,
                        max: 128,
                        message: (this.$route.meta.title+"").substring(0,2)+'名称长度为1-128个字符',
                        trigger: 'change'
                    },
                    {
                        validator: validateName128,
                        trigger: 'change'
                    }
                ],
                groupIdList: [
                    {
                        required: true,
                        type: 'array',
                        min: 1,
                        message: '请选择实验组',
                        trigger: 'change',
                        validator: validateGroup
                    }
                ],
                groupList: [
                    {
                        required: true,
                        type: 'array',
                        min: 1,
                        validator: validateGroupUserNum,
                        trigger: 'change'
                    }
                ],
                description:[
                    {
                        required: true,
                        max: 128,
                        message: '描述长度为1-128个字符',
                        trigger: 'change'
                    }
                ]
            },
            planCol: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'left'
                },
                { title: '名称', key: 'name', minWidth: 100, tooltip: true },
                {
                    title: (this.$route.meta.title+"").substring(0,2)+'类型',
                    key: 'egType',
                    width: 120,
                    filter: (egType) => {
                        return egType === 'exam' ? '考试' : '课件';
                    }
                },
                {
                    title: (this.$route.meta.title+"").substring(0,2)+'形式',
                    key: 'type',
                    width: 120,
                    render: (h, params) => {
                        let optionArr = params.row.typeList.map((item) => {
                            return h(
                                'Option',
                                {
                                    props: {
                                        value: item.key
                                    }
                                },
                                item.title
                            );
                        });
                        if (optionArr.length > 1) {
                            return h(
                                'FormItem',
                                {
                                    props: {
                                        'label-width': 0,
                                        rules: {
                                            type: 'number',
                                            required: true,
                                            message: '不能为空',
                                            trigger: 'change',
                                            validator: (rule, value, callback) => {
                                                if (params.row.type || params.row.type === 0) {
                                                    callback();
                                                } else {
                                                    callback('不能为空');
                                                }
                                            }
                                        },
                                        // showMessage: false,
                                        prop: 'planList.' + params.index + '.type'
                                    },
                                    style: {
                                        margin: 0,
                                        width: '100%'
                                    }
                                },
                                [
                                    h(
                                        'Select',
                                        {
                                            props: {
                                                transfer: true,
                                                placeholder: '请选择',
                                                value: params.row.type
                                            },
                                            on: {
                                                'on-change': (type) => {
                                                    params.row.type = this.planValidate.planList[
                                                        params.index
                                                    ].type = type;
                                                    // this.formData.planList[params.index].type = type;
                                                    this.planValidate.planList[
                                                        params.index
                                                    ].classTypeList = params.row.classTypeList = this.classTypeList.filter(
                                                        (item) => item.type === type
                                                    );
                                                    let planList = JSON.stringify(this.planValidate.planList)
                                                    this.planValidate.planList=this.planValidate.planList.splice(0,this.planValidate.planList.length,JSON.parse(planList))
                                                    // this.formData.planList[params.index].type = type;
                                                    if (params.row.classTypeList.length === 1) {
                                                        params.row.classType = this.planValidate.planList[
                                                            params.index
                                                        ].classType =
                                                            params.row.classTypeList[0].key;
                                                    } else if (
                                                        params.row.classTypeList.length === 0
                                                    ) {
                                                        params.row.classType = this.planValidate.planList[
                                                            params.index
                                                        ].classType = '';
                                                    }
                                                }
                                            }
                                        },
                                        optionArr
                                    )
                                ]
                            );
                        } else {
                            return h('span', this.filterType(params.row.type));
                        }
                    }
                },
                {
                    title: '上课模式',
                    key: 'classType',
                    minWidth: 120,
                    render: (h, params) => {
                        if (!params.row.classTypeList) {
                            return h('span', '-');
                        }
                        let optionArr = params.row.classTypeList.map((item) => {
                            return h(
                                'Option',
                                {
                                    props: {
                                        value: item.key
                                    }
                                },
                                item.title
                            );
                        });
                        if (optionArr.length > 0) {
                            return h(
                                'FormItem',
                                {
                                    props: {
                                        'label-width': 0,
                                        rules: {
                                            type: 'string',
                                            required: true,
                                            message: '不能为空',
                                            trigger: 'change',
                                            validator: (rule, value, callback) => {
                                                if (params.row.classType) {
                                                    callback();
                                                } else {
                                                    callback('不能为空');
                                                }
                                            }
                                        },
                                        // showMessage: false,
                                        prop: 'planList.' + params.index + '.classType'
                                    },
                                    style: {
                                        margin: 0,
                                        width: '100%'
                                    }
                                },
                                [
                                    h(
                                        'Select',
                                        {
                                            props: {
                                                transfer: true,
                                                placeholder: '请选择',
                                                value: params.row.classType
                                            },
                                            on: {
                                                'on-change': (classType) => {
                                                    params.row.classType = this.planValidate.planList[
                                                        params.index
                                                    ].classType = classType;
                                                    this.$refs['planValidate'].validateField(
                                                        'planList.' + params.index + '.classType'
                                                    );
                                                }
                                            }
                                        },
                                        optionArr
                                    )
                                ]
                            );
                        } else {
                            return h('span', this.filterClassType(params.row.classType));
                        }
                    }
                },
                {
                    title: (this.$route.meta.title+"").substring(0,2)+'时间',
                    key: 'time',
                    minWidth: 300,
                    render: (h, params) => {
                        return h(
                            'FormItem',
                            {
                                props: {
                                    'label-width': 0,
                                    rules: {
                                        type: 'array',
                                        // required: true,
                                        // message: '时间不能为空',
                                        trigger: 'blur',
                                        validator: (rule, value, callback) => {
                                            return validateTime(
                                                rule,
                                                params.row.time,
                                                callback,
                                                params.row
                                            );
                                        }
                                    },
                                    // showMessage: false,
                                    // this.planValidate.planList
                                    prop: 'planList.' + params.index + '.time'
                                },
                                attrs: {
                                    title: params.row.timeTip
                                },
                                style: {
                                    margin: 0,
                                    width: '100%'
                                },
                                key: params.row.id,
                                ref: `time-${params.index}`
                            },
                            [
                                h('DatePicker', {
                                    key: params.row.id,
                                    props: {
                                        confirm: true,
                                        value: params.row.time,
                                        type: 'datetimerange',
                                        format: 'yyyy-MM-dd HH:mm',
                                        placeholder: '请选择时间',
                                        options: {
                                            disabledDate(date) {
                                                return (
                                                    date && date.valueOf() < Date.now() - 86400000
                                                );
                                            }
                                        },
                                        transfer: true
                                    },
                                    ref: `datepicker-${params.index}`,
                                    style: {
                                        width: '100%'
                                    },
                                    on: {
                                        'on-change': (time) => {
                                            params.row.selectTime = time;
                                            if (
                                                time &&
                                                time.length === 2 &&
                                                new Date(time[0]).getTime() < new Date().getTime()
                                            ) {
                                                params.row.selectTime[0] = moment(
                                                    new Date().getTime() + 3 * 60 * 1000
                                                ).format('YYYY-MM-DD HH:mm');
                                            }
                                            if (
                                                time &&
                                                time.length === 2 &&
                                                new Date(time[1]).getTime() < new Date().getTime()
                                            ) {
                                                params.row.selectTime[1] = moment(
                                                    new Date().getTime() + 5 * 60 * 1000
                                                ).format('YYYY-MM-DD HH:mm');
                                            }
                                        },
                                        'on-ok': (time) => {
                                            params.row.isClickOkBtn = this.planValidate.planList[
                                                params.index
                                            ].isClickOkBtn = true;
                                            this.curModPlan = params.row;
                                            params.row.time = this.planValidate.planList[
                                                params.index
                                            ].time = params.row.selectTime;
                                            this.planValidate.planList.sort((a, b) => {
                                                if (a.time.length === 2 && b.time.length === 2) {
                                                    return (
                                                        new Date(a.time[0]).getTime() -
                                                        new Date(b.time[0]).getTime()
                                                    );
                                                } else if (
                                                    b.time.length === 2 &&
                                                    (!a.time || a.time.length === 0)
                                                ) {
                                                    return 1;
                                                }
                                            });
                                            this.planValidate.planList.forEach((plan, index) => {
                                                if (plan.time.length === 2) {
                                                    this.$refs['planValidate'].validateField(
                                                        'planList.' + index + '.time'
                                                    );
                                                }
                                            });
                                        },
                                        'on-clear': () => {
                                            params.row.time = this.planValidate.planList[
                                                params.index
                                            ].time = [];
                                        },
                                        'on-open-change': (isOpen) => {
                                            this.$nextTick(() => {
                                                if (isOpen) {
                                                    // 显示组件
                                                    params.row.isClickOkBtn = this.planValidate.planList[
                                                        params.index
                                                    ].isClickOkBtn = false;
                                                    params.row.originalTime = this.planValidate.planList[
                                                        params.index
                                                    ].originalTime = params.row.time;
                                                } else {
                                                    // 隐藏操作
                                                    if (!params.row.isClickOkBtn) {
                                                        // 不是通过点击确认按钮关闭DatePicker组件时，复原时间
                                                        params.row.time = this.planValidate.planList[
                                                            params.index
                                                        ].time = params.row.originalTime;
                                                        if (
                                                            !params.row.originalTime ||
                                                            params.row.originalTime.length === 0
                                                        ) {
                                                            this.$refs['selectTable'].$refs[
                                                                `datepicker-${params.index}`
                                                            ].handleClear();
                                                        }
                                                    }
                                                }
                                            });
                                        }
                                    }
                                })
                            ]
                        );
                    }
                }
                // {
                //     title:'操作',
                //     slot:"action",
                //     opList:[{
                //             txt:'删除',
                //             type:'delete',
                //             tooltip:true,
                //             title:'确认删除'?
                //         }
                //     ]
                // }
            ],

            pickerOptions: {
                disabledDate(date) {
                    return date && date.valueOf() < Date.now() - 86400000;
                }
            },
            timeTip: '',
            allowStep: true,
            stepLoading: false,
            confirmLoading: false,
            hasChatGroup: false
        };
    },
    computed: {
        pageSTitle () { // 小菜单明
          //当前菜单显示名
          return (this.$route.meta.title+"").substring(0,2);
        },
        showPlanList() {
            return this.planValidate.planList.sort((a, b) => {
                return new Date(a.startTime).getTime() - new Date(b.startTime).getTime();
            });
        },
        allSelectUserIds() {
            let ids = [];
            this.formValidate.groupList.forEach((group) => {
                ids = ids.concat(group.userIds);
            });
            return ids;
        }
    },
    watch: {
        'addClassModal.show': {
            handler: function(val) {
                if (!val) {
                    this.$emit('input', false);
                    this.$emit('close');
                }
            },
            deep: true
        },
        value(val) {
            if (val) {
                this.showModal();
            } else {
                this.addClassModal.show = val;
            }
        }
    },
    mounted() {
        this.planValidate.planList = [];
    },
    methods: {
        async showModal() {
            this.initData();
            this.requestIds = [];
            await this.getExpGroupList();
            if (this.type === 'update') {
                this.addClassModal.title = '编辑'+this.pageSTitle;
                this.getClassInfo(this.data);
                this.getChatGroupInfo(this.data.id);
            } else {
                this.resetField('formValidate');
                this.formValidate.teacherId = this.USER_ID;
                this.formValidate.teacherName = this.USER_NAME;
                this.addClassModal.title = '创建'+this.pageSTitle;
            }
        },
        initData() {
            //初始化数据
            let September = sessionStorage.getItem('November');
            September = JSON.parse(encryption.SelfUseDecrypt(September));
            this.USER_ID = September.userId;
            this.USER_NAME = September.nickname;
            this.allowStep = true;
            this.stepLoading = false;
            this.confirmLoading = false;
            this.addClassModal = {
                show: this.value,
                title: '创建'+this.pageSTitle,
                loading: true,
                step: 1,
                courseList: [],
                expList: [],
                skillList: [], //技能书列表
                query: { skillId: '' }
            };
            this.formValidate = {
                description: '',
                egName: '',
                teacherName: '',
                userList: [],
                selectUsers: [],
                groupIdList: [],
                groupList: [],
                teacherId: this.USER_ID,
                teacherName: this.USER_NAME,
                trainUserTOS: [
                    {
                        groupId: '',
                        groupName: '',
                        userId: '',
                        userName: ''
                    }
                ]
            };
            this.planValidate = {
                planList: [],
                selectPlans: [],
                planTotal: 0,
                savedPlanInfo: {
                    list: [],
                    total: '',
                    page: 1,
                    size: 10
                } //已保存的课节课节列表
            };
        },
        //查询培训列表详情
        async getClassInfo(classInfo) {
            let params = {
                pageIndex: 1,
                pageSize: 1000
            };
            let userList = [];
            let { code, data, message } = await queryClassInfo(classInfo.id).catch((error) => {
                console.log(error);
            });
            if (code === 1) {
                userList = data.trainUserList;
                this.storeUserList = data.trainUserList;
            } else {
                this.$Message.error(message);
            }
            let formValidate = JSON.parse(JSON.stringify(classInfo));
            this.saveUsers = userList.filter((user) => !user.teacher);
            this.formValidate = Object.assign(formValidate, {
                groupIdList: [...new Set(userList.map((user) => user.groupId))],
                groupList: []
            });
            this.addClassModal.show = true;
        },
        intoStep(step) {
            if (step === 2) {
                if (this.addClassModal.step === 1) {
                    this.saveClass();
                }
            } else {
                this.addClassModal.step = step;
            }
        },
        switchStep() {
            if (this.addClassModal.step === 1) {
                this.saveClass();
            } else {
                this.addClassModal.step = 1;
                this.allowStep = true;
            }
        },
        //保存培训
        saveClass () {
            console.log('==class_new===');
            this.stepLoading = true;
            this.$refs['formValidate']
                .validate((valid) => {
                    if (valid) {
                        let userList = [],
                            userIds = [];
                        this.formValidate.groupList.forEach((group) => {
                            group.userList.forEach((user) => {
                                if (
                                    !userIds.includes(user.userId) &&
                                    group.userIds.includes(user.userId)
                                ) {
                                    userList.push({
                                        groupId: group.id,
                                        groupName: group.name,
                                        userId: user.userId,
                                        userName: user.userName
                                    });
                                    userIds.push(user.userId);
                                }
                            });
                        });
                        let params = {
                            description: this.formValidate.description,
                            egName: this.formValidate.egName,
                            teacherName: this.formValidate.teacherName,
                            trainUserTOS: userList
                        };
                        if (!this.formValidate.id) {
                            addClass(params)
                                .then((data) => {
                                    this.cancelLoading('addClassModal');
                                    if (data.code == 1) {
                                        // this.resetField('formValidate');
                                        //this.addClassModal.show = false;
                                        //this.refreshMyClassList(); //清空所有查询条件，回到第一页
                                        //this.$Message.info(data.message);
                                        //创建自定义群组
                                        this.addGroup(data.data, userList, 'add');
                                        this.formValidate.id = data.data;
                                        this.addClassModal.step = 2;
                                        this.saveUsers = userList;
                                        // this.querySkillList();
                                    } else {
                                        this.$Message.warning(data.message);
                                    }
                                    this.stepLoading = false;
                                })
                                .catch((error) => {
                                    this.stepLoading = false;
                                    this.cancelLoading('addClassModal');
                                });
                        } else {
                            modifyClass(this.formValidate.id, params)
                                .then((data) => {
                                    this.cancelLoading('addClassModal');
                                    if (data.code == 1) {
                                        // this.resetField('formValidate');
                                        // this.addClassModal.show = false;
                                        // this.queryClassList();
                                        this.addClassModal.step = 2;
                                        this.saveUsers = userList;
                                        if (!this.hasChatGroup) {
                                            //创建自定义群组
                                            this.addGroup(this.formValidate.id, userList, 'add');
                                        } else {
                                            // 编辑成员
                                            this.addGroup(this.formValidate.id, userList, 'modify');
                                        }
                                        // this.querySkillList();
                                        // this.$Message.info(data.message);
                                    } else {
                                        this.$Message.warning(data.message);
                                    }
                                    this.stepLoading = false;
                                })
                                .catch((error) => {
                                    this.cancelLoading('addClassModal');
                                    this.stepLoading = false;
                                });
                        }
                    } else {
                        this.stepLoading = false;
                        this.cancelLoading('addClassModal');
                    }
                })
                .catch((error) => {
                    this.stepLoading = false;
                    console.log(error);
                });
        },
        //创建聊天组
        addGroup(groupId, userList, op) {
            let groupUsers = userList.map((user) => {
                return {
                    avatar: '',
                    userId: user.userId,
                    userName: user.userName
                };
            });
            groupUsers.push({
                avatar: '',
                userId: this.formValidate.teacherId,
                userName: this.formValidate.teacherName
            });
            let params = {
                avatar: '',
                id: groupId,
                name: this.formValidate.egName,
                groupUsers: groupUsers
            };
            if (op === 'add') {
                addGroup(params)
                    .then((data) => {
                        if (data.code == 1) {
                            this.hasChatGroup = true;
                            // if (needShowTip) {
                            //     this.$Message.info('聊天组创建成功');
                            //     groupInfo.hasChatGroup = true;
                            // }
                        } else {
                            this.$Message.error(data.message);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            } else if (op === 'modify') {
                updateGroup(params).then((data) => {
                    if (data.code == 1) {
                        // if (needShowTip) {
                        //     this.$Message.info('聊天组编辑成功');
                        //     groupInfo.hasChatGroup = true;
                        // }
                    } else {
                        this.$Message.error(data.message);
                    }
                });
            }
        },
        getChatGroupInfo(id) {
            getGroupInfo(id)
                .then((res) => {
                    if (res.code && res.data.data) {
                        this.hasChatGroup = true;
                    } else {
                        this.hasChatGroup = false;
                    }
                })
                .catch((error) => {
                    this.hasChatGroup = true;
                });
        },
        //取消按钮loading
        cancelLoading(name) {
            this[name].loading = false;
            setTimeout(() => {
                this[name].loading = true;
            });
        },
        //重置表单
        resetField(name) {
            this.$refs[name].resetFields();
            this.formValidate = {
                description: '',
                egName: '',
                teacherName: '',
                userList: [],
                selectUsers: [],
                groupIdList: [],
                groupList: [],
                trainUserTOS: [
                    {
                        groupId: '',
                        groupName: '',
                        userId: '',
                        userName: ''
                    }
                ]
            };
            // this.clearSelectUser();
        },
        //查询实验组
        getExpGroupList() {
            return new Promise((resolve, reject) => {
                let params = {
                    visibility: 'all',
                    order: 'desc',
                    sortBy: 'created',
                    pageIndex: 1,
                    pageSize: 2147483646
                };
                queryExperGroups(params).then((data) => {
                    if (data.code == 1) {
                        this.expGroupList = data.data.items.filter((item) => item.userCount > 0);
                        resolve();
                    } else {
                        this.$Message.warning(data.message);
                    }
                });
            });
        },
        changeGroup(ids) {
            this.getGroupUsers(ids);
        },
        //查询实验组成员--change实验组时调用
        async getGroupUsers(ids, initSelectUsers) {
            // return new Promise((resolve, reject) => {
            console.log('查询实验组成员啊啊啊---------')
            let preGroupList = [...this.formValidate.groupList];
            let preIds = preGroupList.map((group) => group.id);
            this.formValidate.groupList = [];
            if (!ids || ids.length === 0) {
                return;
            }
            this.allowStep = false;
                      let pArr = ids
                      .map((groupId) => {
                    let group = this.expGroupList.find((expGroup) => expGroup.id === groupId);
                    if ((group.userList&&group.userList.length>0) || this.requestIds.includes(groupId)) {
                        return;
                    }
                    return new Promise((resolve, reject) => {
                        this.requestIds.push(groupId);
                        getExperGroupsUsers(groupId)
                            .then(({ code, data, message }) => {
                                let userList = data;
                                group.userList = userList.map((user) => {
                                    return {
                                        id: user.id,
                                        userId: user.userId,
                                        userName: user.user.nickname
                                    };
                                });
                                resolve(userList);
                            })
                            .catch((error) => {
                                console.log(error);
                            });
                    });
                })
                .filter((res) => res);
            pArr.length > 0 && (await Promise.all(pArr));
            ids.forEach((groupId) => {
                if (preIds.includes(groupId)) {
                    let group = preGroupList.find((group) => group.id === groupId);
                    this.formValidate.groupList.push(group);
                } else {
                    let group = JSON.parse(
                        JSON.stringify(
                            this.expGroupList.find((expGroup) => expGroup.id === groupId)
                        )
                    );
                    this.$set(group, 'checkAll', true);
                    this.$set(group, 'disabled', false);
                    this.$set(group, 'userIds', []);
                    if (group.userList) {
                        let userList = group.userList;
                        if (this.saveUsers && this.saveUsers.length > 0) {
                            group.userIds = this.saveUsers
                                .filter(
                                    (user) =>
                                        user.groupId === group.id &&
                                        !this.disUserSelect(user, group)
                                )
                                .map((user) => user.userId);
                        } else {
                            group.checkAll = true;
                            group.userIds = userList
                                .filter((user) => !this.disUserSelect(user, group))
                                .map((user) => user.userId);
                        }
                    }
                    this.formValidate.groupList.push(group);
                }
            });
            this.handleGroupChange();
            this.saveUsers = [];
            this.allowStep = true;
            // });
            // resolve();
            // });
        },
        disUserSelect(user, group) {
            let ids = [];
            this.formValidate.groupList
                .filter((item) => item.id != group.id)
                .forEach((item) => {
                    ids = ids.concat(item.userIds);
                });
            return ids.includes(user.userId);
        },
        handleCheckAll(group) {
            group.checkAll = !group.checkAll;
            if (group.checkAll) {
                group.userIds = group.userList
                    .filter((user) => !this.disUserSelect(user, group))
                    .map((user) => user.userId);
            } else {
                group.userIds = [];
            }
        },
        handleGroupChange(userIds, userGroup) {
            this.formValidate.groupList.forEach((group, index) => {
                let data = group.userIds;
                if (
                    data.length ===
                    group.userList.filter((user) => !this.disUserSelect(user, group)).length
                ) {
                    group.checkAll = true;
                } else {
                    group.checkAll = false;
                }
            });
        },
        // selectData(selection) {
        //     this.planValidate.selectPlans = selection;
        // },
        addTrain(selection) {
            let list = selection;
            let ids = this.planValidate.planList.map((item) => item.id);
            list.forEach((planItem, index) => {
                planItem.time = [];
                planItem.egType = planItem.setType === 1 ? 'exp' : 'exam';
                planItem.type = '';
                planItem.classType = '';
                if (planItem.egType === 'exp' && planItem.expType !== 0) {
                    //非实操课件只能作为作业
                    planItem.type = 1;
                } else if (planItem.egType === 'exam') {
                    planItem.type = 2;
                }
                planItem.typeList = this.typeList.filter((item) => {
                    return (
                        item.egType === planItem.egType &&
                        (planItem.expType ? item.optionalExpType.includes(planItem.expType) : true)
                    );
                });
                planItem.classTypeList = this.classTypeList.filter(
                    (item) => item.type === planItem.type
                );
                if (!ids.includes(planItem.id)) {
                    this.planValidate.planList.push(planItem);
                    this.planValidate.planTotal += 1;
                }
                // planItem.id = 'ECIDa4adb3f442ccac925a80944fd5d2';
                // planItem.name = '【WooYun-2015-110216】Elasticsearch写入webshell漏洞';
            });
        },
        delSelect() {
            if (this.planValidate.selectPlans.length === 0) {
                this.$Message.info('请选择要删除的数据');
                return;
            }
            let list = this.planValidate.planList.slice();
            this.planValidate.planList = [];
            this.planValidate.planList = list.filter(
                (item) => !this.planValidate.selectPlans.map((item) => item.id).includes(item.id)
            );
            this.clearSelectUser();
            this.planValidate.planList.forEach((plan, index) => {
                if (plan.time.lenght === 2) {
                    this.$refs['planValidate'].validateField('planList.' + index + '.time');
                }
            });
            this.$Message.info('删除成功');
        },
        handleClose(item) {
            this.$refs.selectTable.closeItem(item);
        },
        clearSelectUser() {
            this.$refs.selectTable.clearSelect();
        },
        //获取技能书列表
        querySkillList(type) {
            let params = {
                pageIndex: 1,
                pageSize: 10000,
                available: 1
            };
            querySkill(params)
                .then((data) => {
                    if (data.code === 1) {
                        this.addClassModal.skillList = data.data.items;
                    } else {
                        this.$Message.error(data.message);
                    }
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        getSkillDtail(id) {
            let params = {
                id: id,
                pageIndex: 1,
                pageSize: 10000,
                type: [1, 3]
            };
            querySkillBindDetail(params).then(({ code, data, message }) => {
                if (code === 1) {
                    let list = data.items;
                    list.forEach((planItem, index) => {
                        planItem.time = [];
                        planItem.egType = planItem.type === 1 ? 'exp' : 'exam';
                        planItem.type = '';
                        planItem.classType = '';
                        planItem.typeList = this.typeList.filter(
                            (item) => item.egType === planItem.egType
                        );
                        planItem.classTypeList = this.classTypeList.filter(
                            (item) => item.type === planItem.type
                        );
                        // planItem.id = 'ECIDa4adb3f442ccac925a80944fd5d2';
                        // planItem.name = '【WooYun-2015-110216】Elasticsearch写入webshell漏洞';
                    });
                    this.planValidate.planTotal = list.length;
                    this.planValidate.planList = list;
                }
            });
        },
        saveTeachSchedule() {
            this.addTeachSchedule();
        },
        addTeachSchedule() {
            if (this.planValidate.planList.length === 0) {
                this.confirmLoading = false;
                // this.$Message.info('请创建培训内容');
                // this.edit.show = false;
                this.addClassModal.show = false;
                return;
            }
            this.confirmLoading = true;
            this.$refs['planValidate']
                .validate((valid) => {
                    console.log(this.planValidate.planList, this.showPlanList);
                    if (valid) {
                        this.timeTip = '';
                        let data = this.planValidate.planList.map((item) => {
                            let { classType, name, egType, type, id: exId, totalScore } = item;
                            let startTime = item.time[0] + ':00',
                                endTime = item.time[1] + ':00';
                            return {
                                classType, //上课模式
                                egId: this.formValidate.id, //培训id
                                cnStatus: 0,
                                egType, //培训类型
                                type, //形式
                                endTime,
                                paperId: egType === 'exam' ? exId : '',
                                exId: egType === 'exam' ? '' : exId, //课件id或试卷id
                                name,
                                paperName: name, //试卷名称
                                paperScore: totalScore, //试卷分数
                                startTime
                            };
                        });
                        addTeachSchedule(data)
                            .then(({ code, data, message }) => {
                                if (code === 1) {
                                    this.$Message.info('保存成功');
                                    this.addClassModal.show = false;
                                    this.$emit('updateList')
                                } else {
                                    this.$Message.error(message);
                                }
                                this.confirmLoading = false;
                            })
                            .catch((error) => {
                                this.confirmLoading = false;
                            });
                    } else {
                        // if (this.planValidate.planList.some((plan) => plan.time.length === 0)) {
                        //     this.timeTip = '请选择培训时间';
                        // } else if (
                        //     this.planValidate.planList.some(
                        //         (plan) => plan.timeTip === '培训时间冲突'
                        //     )
                        // ) {
                        //     this.timeTip = '培训时间冲突';
                        // }
                        this.confirmLoading = false;
                    }
                })
                .catch((error) => {
                    this.confirmLoading = false;
                });
        },
        queryTeachSchedule() {
            if (!this.formValidate.id) {
                return;
            }
            return new Promise((resolve, reject) => {
                let params = {
                    pageIndex: this.planValidate.savedPlanInfo.page,
                    pageSize: this.planValidate.savedPlanInfo.size,
                    egId: this.formValidate.id
                };
                queryTeachSchedule(params)
                    .then(({ code, attribute: data, message }) => {
                        if (code === 1) {
                            this.planValidate.savedPlanInfo.list = data.dataList;
                            this.planValidate.savedPlanInfo.total = data.totalCount;
                            resolve();
                        } else {
                            this.$Message.error(message);
                        }
                    })
                    .catch((error) => {});
            });
        },
        showAddModal() {
            this.addModal.show = true;
        }
    }
};
</script>
<style scoped>
.header-wrapper {
  margin-bottom: 10px;
}
.step-group {
  display: flex;
}
.step-group .ivu-btn-text {
  color: var(--default-color-level2);
}
/deep/.class-card .ivu-card-head {
  flex: none;
  border-right: 1px solid var(--card-line-color);
  border-bottom: none;
}
.flex-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex {
  display: flex;
  align-items: center;
}
.mr10 {
  margin-right: 10px;
}
.mt10 {
  margin-top: 10px;
}
.mr10 {
  margin-right: 10px;
}
</style>
